//
//  PerfectInfoViewController.swift
//  Liao
//
//  Created by 范东 on 2022/1/30.
//

import UIKit
import FDUIKit
import FDNetwork

class PerfectInfoViewController: BaseViewController {
    
    var userId = ""
    
    var fullInfo = V2TIMUserFullInfo()

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        
        view.addSubview(iconImageView)
        view.addSubview(nameTextField)
        view.addSubview(maleBtn)
        view.addSubview(femaleBtn)
        view.addSubview(saveBtn)
        
        iconImageView.snp.makeConstraints { make in
            make.top.equalToSuperview().offset(20+CGFloat.navigationBarHeight)
            make.size.equalTo(CGSize(width: 100, height: 100))
            make.centerX.equalToSuperview()
        }
        nameTextField.snp.makeConstraints { make in
            make.top.equalTo(self.iconImageView.snp.bottom).offset(20)
            make.left.equalToSuperview().offset(20)
            make.right.equalToSuperview().offset(-20)
            make.height.equalTo(50)
        }
        maleBtn.snp.makeConstraints { make in
            make.top.equalTo(self.nameTextField.snp.bottom).offset(20)
            make.left.equalToSuperview().offset(20)
            make.height.equalTo(50)
        }
        femaleBtn.snp.makeConstraints { make in
            make.top.equalTo(self.nameTextField.snp.bottom).offset(20)
            make.left.equalTo(self.maleBtn.snp.right).offset(20)
            make.right.equalToSuperview().offset(-20)
            make.width.equalTo(self.maleBtn.snp.width)
            make.height.equalTo(50)
        }
        saveBtn.snp.makeConstraints { make in
            make.top.equalTo(self.femaleBtn.snp.bottom).offset(20)
            make.left.equalToSuperview().offset(20)
            make.right.equalToSuperview().offset(-20)
            make.height.equalTo(50)
        }
    }
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        super.touchesBegan(touches, with: event)
        view.endEditing(true)
    }
    
    @objc func saveBtnAction(){
        if fullInfo.gender == .GENDER_UNKNOWN {
            FDMessageView.show(title: NSLocalizedString("Warning", comment:""), message: NSLocalizedString("No Sex", comment: ""), theme: .warning)
            return
        }
        fullInfo.customInfo["Coin"] = "0".data(using: .utf8)
        V2TIMManager.sharedInstance().setSelfInfo(fullInfo) {
            self.dismiss(animated: true, completion: nil)
        } fail: { code, msg in
            FDMessageView.show(title: NSLocalizedString("Error", comment:""), message: msg ?? "", theme: .error)
        }
    }
    
    @objc func iconImageViewAction(){
        let alert = UIAlertController(title: NSLocalizedString("Tip", comment: ""), message: nil, preferredStyle: .actionSheet)
        alert.addAction(UIAlertAction(title: NSLocalizedString("Camera", comment: ""), style: .default, handler: { action in
            let picker = UIImagePickerController()
            picker.delegate = self
            picker.mediaTypes = ["public.image"]
            picker.sourceType = .camera
            picker.allowsEditing = true
            self.present(picker, animated: true, completion: nil)
        }))
        alert.addAction(UIAlertAction(title: NSLocalizedString("PhotoLibrary", comment: ""), style: .default, handler: { action in
            let picker = UIImagePickerController()
            picker.delegate = self
            picker.mediaTypes = ["public.image"]
            picker.sourceType = .photoLibrary
            picker.allowsEditing = true
            self.present(picker, animated: true, completion: nil)
        }))
        alert.addAction(UIAlertAction(title: NSLocalizedString("Cancel", comment: ""), style: .cancel, handler: nil))
        present(alert, animated: true, completion: nil)
    }
    
    @objc func maleBtnAction(sender: UIButton){
        sender.isSelected = true
        sender.backgroundColor = .systemBlue
        femaleBtn.isSelected = false
        femaleBtn.backgroundColor = .white
        fullInfo.gender = .GENDER_MALE
    }
    
    @objc func femaleBtnAction(sender: UIButton){
        sender.isSelected = true
        sender.backgroundColor = .systemBlue
        maleBtn.isSelected = false
        maleBtn.backgroundColor = .white
        fullInfo.gender = .GENDER_FEMALE
    }

    lazy var iconImageView: UIImageView = {
        let iconImageView = UIImageView(frame: .zero)
        iconImageView.layer.cornerRadius = 50
        iconImageView.clipsToBounds = true
        iconImageView.isUserInteractionEnabled = true
        iconImageView.contentMode = .scaleAspectFill
        iconImageView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(iconImageViewAction)))
        return iconImageView
    }()
    
    lazy var nameTextField: UITextField = {
        let nameTextField = UITextField(frame: .zero)
        nameTextField.borderStyle = .roundedRect
        nameTextField.placeholder = NSLocalizedString("NickName", comment: "")
        nameTextField.font = .systemFont(ofSize: 16, weight: .medium)
        nameTextField.textColor = .systemGray
        nameTextField.delegate = self
        return nameTextField
    }()
    
    lazy var maleBtn: UIButton = {
        let maleBtn = UIButton(frame: .zero)
        maleBtn.setTitle(NSLocalizedString("Male", comment: ""), for: .normal)
        maleBtn.setTitleColor(.systemBlue, for: .normal)
        maleBtn.setTitleColor(.white, for: .selected)
        maleBtn.layer.cornerRadius = 10
        maleBtn.clipsToBounds = true
        maleBtn.layer.borderColor = UIColor.systemBlue.cgColor
        maleBtn.layer.borderWidth = 0.5
        maleBtn.titleLabel?.font = .systemFont(ofSize: 16, weight: .medium)
        maleBtn.addTarget(self, action: #selector(maleBtnAction(sender:)), for: .touchUpInside)
        return maleBtn
    }()
    
    lazy var femaleBtn: UIButton = {
        let femaleBtn = UIButton(frame: .zero)
        femaleBtn.setTitle(NSLocalizedString("Female", comment: ""), for: .normal)
        femaleBtn.setTitleColor(.systemBlue, for: .normal)
        femaleBtn.setTitleColor(.white, for: .selected)
        femaleBtn.layer.cornerRadius = 10
        femaleBtn.clipsToBounds = true
        femaleBtn.layer.borderColor = UIColor.systemBlue.cgColor
        femaleBtn.layer.borderWidth = 0.5
        femaleBtn.titleLabel?.font = .systemFont(ofSize: 16, weight: .medium)
        femaleBtn.addTarget(self, action: #selector(femaleBtnAction(sender:)), for: .touchUpInside)
        return femaleBtn
    }()
    
    
    lazy var saveBtn: UIButton = {
        let saveBtn = UIButton(frame: .zero)
        saveBtn.backgroundColor = .systemBlue
        saveBtn.setTitle(NSLocalizedString("Save", comment: ""), for: .normal)
        saveBtn.layer.cornerRadius = 10
        saveBtn.clipsToBounds = true
        saveBtn.titleLabel?.font = .systemFont(ofSize: 16, weight: .medium)
        saveBtn.addTarget(self, action: #selector(saveBtnAction), for: .touchUpInside)
        return saveBtn
    }()

}

extension PerfectInfoViewController: UITextFieldDelegate{
    func textFieldDidChangeSelection(_ textField: UITextField) {
        fullInfo.nickName = textField.text
    }
}

extension PerfectInfoViewController: UIImagePickerControllerDelegate,UINavigationControllerDelegate{
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
        let originalImage = info[.editedImage] as! UIImage
        let fileKey = "\(FMRadio.getUserId())"+"-avatar-"+"\(Date().timeIntervalSince1970)"+".png"
        picker.dismiss(animated: true) {
            FDNetwork.GET(url: "http://api.video.app.xiaobingkj.com/api/api/getUploadToken", param: [:]) { result in
                let resultDict = result as! [String: Any]
                let dataDict = resultDict["data"] as! [String: String]
                let token = dataDict["token"]
                let domain = dataDict["domain"]
                let upManager = QNUploadManager()
                let data = originalImage.pngData()
                upManager?.put(data, key: fileKey, token: token, complete: { info, key, resp in
                    self.iconImageView.image = originalImage
                    self.fullInfo.faceURL = domain!+(key ?? "")
                }, option: QNUploadOption())
            } failure: { error in
                FDMessageView.show(title: NSLocalizedString("Tip", comment: ""), message: error, theme: .error)
            }
        }
    }
}
